package cn.client.ui.view.signIn

import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.NavGraph.Companion.findStartDestination
import cn.client.R
import cn.client.navigation.destinations.SignInSecond
import cn.client.ui.view.signIn.SignInViewModel
import cn.client.ui.view.signUp.SignUpViewModel
import kotlinx.coroutines.launch


/**
 * 登录：第一步
 */
@Composable
fun SignInFirstPage(
    navController: NavController,
    //  获取ViewModel实例
    viewModel: SignInViewModel = hiltViewModel()
) {
    val context = LocalContext.current
    var showDialog by remember { mutableStateOf(false) }
    var account: String by remember { mutableStateOf("") }
    val coroutineScope = rememberCoroutineScope()
    // 观察ViewModel中的状态
    val states = viewModel.pageStates

    //  使用LaunchedEffect来启动协程，收集事件
    LaunchedEffect(Unit){
        viewModel.pageEvents.collect {
            if (it is SignInViewModel.PageEvent.Result){
                if (it.result.code==200){
                    Toast.makeText(context,"校验成功", Toast.LENGTH_LONG).show()
                    navController.navigate(SignInSecond.route + "/${account}")
                } else {
                    Toast.makeText(context,"账号 $account 错误 ${states.verifyStatus}", Toast.LENGTH_LONG).show()
                }
            } else if (it is SignInViewModel.PageEvent.Error){
                Toast.makeText(context,"未知错误：${it.error}", Toast.LENGTH_LONG).show()
            }
        }
    }

    Box (
        contentAlignment = Alignment.Center,
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White)
    ){
        Column(
            modifier = Modifier.wrapContentSize(Alignment.Center, false)
        ) {
            /* 间隔距离 */
            Spacer(modifier = Modifier.height(40.dp))
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentSize(Alignment.Center, false)
            ) {
                Text(
                    text = (stringResource(R.string.sign_in)),
                    fontSize = 30.sp, // 字体大小
                    fontWeight = FontWeight.Bold,
                    textAlign = TextAlign.Center,
                    )
            }
            /* 间隔距离 */
            Spacer(modifier = Modifier.height(30.dp))
            /* 输入账号 */
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentSize(Alignment.Center, false)
            ) {
                OutlinedTextField(
                    value = account,
                    label = {  Text(stringResource(R.string.account)) },
                    onValueChange = { str -> account = str },
                    placeholder = { Text(stringResource(R.string.input_account)) },
                    singleLine = true,
                    // 键盘事件
                    keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done),
                    keyboardActions = KeyboardActions(onDone = { }),
                    modifier = Modifier
                        .clip(RoundedCornerShape(20.dp))
                        .fillMaxWidth()
                        .padding(10.dp)
                )
            }
            /* 间隔距离 */
            Spacer(modifier = Modifier.height(20.dp))
            /* 下一步 */
            Row {
                Button(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(10.dp),
                    onClick = {
                        if (account != ""){
                            // 在协程中发送意图
                            coroutineScope.launch {
                                viewModel.dispatch(SignInViewModel.PageIntent.VerifyAccount(account))
                            }
                        } else {
                            // 如果输入的内容为空，弹窗提示
                            showDialog = !showDialog
                        }
                    },
                ) {
                    Text(
                        text = "下一步",
                        textAlign = TextAlign.Center
                    )
                }
            }
        }
    }

    /**
     * 弹窗
     */
    if (showDialog) {
        AlertDialog(
            onDismissRequest = { showDialog = false },
            title = { Text(text = "内容不能为空") },
//            text = { Text(
//                    "This area typically contains the supportive text " +
//                            "which presents the details regarding the Dialog's purpose."
//                )},
            // 确认
            confirmButton = {
                TextButton(
                    onClick = { showDialog = false }
                ) {
                    Text(stringResource(R.string.dialog_confirm))
                }
            },
            // 忽略
//            dismissButton = {
//                TextButton(
//                    onClick = {
//                        showDialog = false
//                    }
//                ) {
//                    Text("Dismiss")
//                }
//            }
        )
    }
}


